package v1

import (
	"gin-example/models"
	"gin-example/pkg/e"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"log"
	"net/http"
)

// 获取全部的成员，按照分类
func GetAllMembers(c *gin.Context) {
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	code := e.SUCCESS

	data["lists"] = models.GetMembers(maps)
	data["total"] = models.GetMembersTotal(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": data,
	})
}

// 增加成员
func AddMember(c *gin.Context) {
	json := make(map[string]string) //注意该结构接受的内容
	_ = c.BindJSON(&json)

	name := json["name"]
	link := json["link"]
	job := json["job"]
	imgUrl := json["img_url"]
	direction := json["direction"]

	valid := validation.Validation{}
	valid.Required(name, "name").Message("名字不能为空")
	valid.Required(imgUrl, "imgUrl").Message("图片地址不能为空")
	valid.Required(direction, "direction").Message("研究方向不能为空")

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		models.AddMember(name, link, job, imgUrl, direction)
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}
var memberFeatures = []string{"link", "job", "graduate", "company", "img_url", "direction"}
// 修改成员
func UpdateMember(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS

	if models.ExistMemberByID(id) {
		code = e.SUCCESS
		json := make(map[string]string) //注意该结构接受的内容
		_ = c.BindJSON(&json)
		data := make(map[string]interface{})
		for _, fea := range memberFeatures {
			if tmp := json[fea]; len(tmp) > 0 {
				if fea == "graduate" {
					data[fea] = com.StrTo(tmp).MustInt()
				} else {
					data[fea] = tmp
				}
			}
		}
		models.UpdateMember(id, data)
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 删除成员
func DeleteMember(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()
	code := e.INVALID_PARAMS
	if models.ExistMemberByID(id) {
		models.DeleteMember(id)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": e.GetMsg(code),
		"data": make(map[string]string),
	})
}
